package com.transn.common.controller;

import com.transn.common.ResultVo;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;


/**
 * 全局配置控制器异常处理
 */
@ControllerAdvice
public class SpringExceptionHandler{

    @ExceptionHandler(value = {UnauthenticatedException.class, UnauthorizedException.class})
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Object handleUnauthenticatedException(final Exception ex, final WebRequest req) {
        String msg = ex.getMessage();
        if(isAjax(req)){
            return new ResponseEntity<Object>(new ResultVo(ResultVo.FAILURE,HttpStatus.UNAUTHORIZED), HttpStatus.UNAUTHORIZED);
        }

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error/401");
        modelAndView.addObject("exception",ex);
        return modelAndView;
    }
  /**
     * 全局处理Exception
     * 错误的情况下返回500
     * @param ex
     * @param req
     * @return
     */
    @ExceptionHandler(value = {Exception.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Object handleOtherExceptions(final Exception ex, final WebRequest req) {
        String msg = ex.getMessage();
        if(isAjax(req)){
            return new ResponseEntity<Object>(new ResultVo(ResultVo.FAILURE,HttpStatus.INTERNAL_SERVER_ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
        }

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error/500");
        modelAndView.addObject("exception",ex);
        return modelAndView;
    }

    boolean isAjax(WebRequest request){
        return  (request.getHeader("X-Requested-With") != null
                && "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With").toString())) ;
    }

}